﻿
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Osiptel.CCPP.UTIL
{

    public class FileUtil
    {
        #region Atributos
        public System.String FilePath { get; set; }
        #endregion

        #region Constructor
        public FileUtil()
        {

        }
        public FileUtil(string filePath)
        {
            this.FilePath = filePath;
        }
        #endregion

        #region Metodos

        #region TXT

        ////OBSOLETO
        //public void leerConstancia(ref Hashtable lcSCD_ConstanciaDetraccionCab, ref List<Hashtable> lcoSCD_ConstanciaDetraccionDetList)
        //{
        //    if (this.FilePath.Trim() != String.Empty)
        //    {

        //        ArrayList alLines = getLines(new StreamReader(this.FilePath,Encoding.Default));                
        //        int indexHeader, indexDetails;
        //        indexHeader = this.getIndexHeader(alLines);
        //        indexDetails = this.getIndexDetails(alLines);
        //        if (indexHeader != 0 && indexDetails != 0)
        //        {
        //            //Obtener Cabecera
        //            int i = indexHeader;
        //            lcSCD_ConstanciaDetraccionCab.Add("NumeroOperacion",this.getValue(alLines[i++]));
        //            lcSCD_ConstanciaDetraccionCab.Add("FechaPago" , DateTime.Parse(this.getValue(alLines[i++])));
        //            lcSCD_ConstanciaDetraccionCab.Add("NombreArchivo", this.getValue(alLines[i++]));
        //            lcSCD_ConstanciaDetraccionCab.Add("NumeroLote", this.getValue(alLines[i++]));
        //            lcSCD_ConstanciaDetraccionCab.Add("ProveedorRUC", this.getValue(alLines[i++]));
        //            lcSCD_ConstanciaDetraccionCab.Add("ProveedorNombre", this.getValue(alLines[i++]));
        //            lcSCD_ConstanciaDetraccionCab.Add("NumeroDepositos", int.Parse(this.getValue(alLines[i++])));
        //            lcSCD_ConstanciaDetraccionCab.Add("MontoTotal", decimal.Parse(this.getValue(alLines[i++])));

        //            i = indexDetails;
        //            //Obtener Detalles
        //            while (i < alLines.Count)
        //            {
        //                if (alLines[i].ToString() != "" && alLines[i] != null)
        //                {
        //                    Hashtable lcoSCD_ConstanciaDetraccionDet = new Hashtable();
        //                    lcoSCD_ConstanciaDetraccionDet.Add("NumeroConstancia", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("ADQUIRIENTERUC",this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("ADQUIRIENTENombre", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("OperacionCodigo", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("OperacionNombre", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("BienServicioCodigo", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("BienServicioNombre", this.getValue(alLines[i++]));
        //                    lcoSCD_ConstanciaDetraccionDet.Add("MontoDeposito", decimal.Parse(this.getValue(alLines[i++])));
        //                    lcoSCD_ConstanciaDetraccionDetList.Add(lcoSCD_ConstanciaDetraccionDet);
        //                }
        //                else
        //                    i++;
        //            }
        //        }
        //        else
        //            throw new Exception(Constantes.MENSAJE.ERROR_LECTURA);
        //    }
        //    else
        //        throw new Exception(Constantes.MENSAJE.ARCHIVO_SIN_NOMBRE);
        //}
        ////FIN OBSOLETO

        public string getFileContent(string filePath)
        {
            return System.IO.File.ReadAllText(filePath);
        }

        public ArrayList getLines(StreamReader streamReader)
        {
            ArrayList alLines = new ArrayList();
            string sLine = "";
            while (sLine != null)
            {
                sLine = streamReader.ReadLine();
                if (sLine != null && sLine.Trim() != "")
                    alLines.Add(sLine);
            }
            streamReader.Close();
            return alLines;

        }

        public string getValue(object line)
        {
            return getValue(line.ToString(), new char[] { '\t' }, 1);
        }

        public string getValue(string line, char[] separator, int index)
        {
            string[] values = line.Split(separator);
            string returnValue;
            try
            {
                returnValue = values[index];
            }
            catch (Exception)
            {
                returnValue = "";
            }
            return returnValue;
        }

        //public int getIndexHeader(ArrayList arrayList)
        //{
        //    int index = 0;
        //    for (int i = 0; i < arrayList.Count; i++)
        //    {
        //        string line = arrayList[i].ToString().Trim();
        //        if (line.IndexOf(Constantes.ARCHIVO.TITULO_CABECERA) >= 0 || line.StartsWith(Constantes.ARCHIVO.TITULO_CABECERA))
        //        {
        //            index = i;
        //            break;
        //        }
        //    }
        //    return index + 1;
        //}

        //public int getIndexDetails(ArrayList arrayList)
        //{
        //    int index = 0;
        //    for (int i = 0; i < arrayList.Count; i++)
        //    {
        //        string line = arrayList[i].ToString().Trim();
        //        if (line.IndexOf(Constantes.ARCHIVO.TITULO_DETALLE) >= 0 || line.StartsWith(Constantes.ARCHIVO.TITULO_DETALLE))
        //        {
        //            index = i;
        //            break;
        //        }
        //    }
        //    return index + 1;
        //}

        public int getRowOfString(ArrayList arrayList, string FindValue)
        {
            int index = 0;
            for (int i = 0; i < arrayList.Count; i++)
            {
                string line = arrayList[i].ToString().Trim();
                if (line.IndexOf(FindValue) >= 0 || line.StartsWith(FindValue))
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

        private string formatLine(string line)
        {
            string newLine = line;
            for (int i = 0; i < newLine.Length; i++)
            {
                newLine = newLine[i].ToString().Replace(UTConstantes.TILDES.A, UTConstantes.TILDESASCII.A);
                newLine = newLine[i].ToString().Replace(UTConstantes.TILDES.E, UTConstantes.TILDESASCII.E);
                newLine = newLine[i].ToString().Replace(UTConstantes.TILDES.I, UTConstantes.TILDESASCII.I);
                newLine = newLine[i].ToString().Replace(UTConstantes.TILDES.O, UTConstantes.TILDESASCII.O);
                newLine = newLine[i].ToString().Replace(UTConstantes.TILDES.U, UTConstantes.TILDESASCII.U);
            }
            return newLine;
        }

        #endregion

        #region Excel

        public System.Data.DataTable leerExcel(string ExcelFile)
        {
            return this.leerExcel(ExcelFile, this.getFirstSheet(ExcelFile));
        }

        public System.Data.DataTable leerExcel(string ExcelFile, string sheet)
        {
            System.Data.DataTable dtExcel = new System.Data.DataTable();
            DataSet dsExcel = new DataSet();
            OleDbConnection lcoOleDbConnection = new OleDbConnection();
            try
            {
                string connectionString = "";
                if (ExcelFile.EndsWith("xls"))
                {
                    connectionString = string.Format(ConfigUtil.readConnectionString("EXCEL_CS"), ExcelFile);
                }
                else
                {
                    connectionString = string.Format(ConfigUtil.readConnectionString("EXCEL_CS_2007"), ExcelFile);
                }
                lcoOleDbConnection = new OleDbConnection(connectionString);
                lcoOleDbConnection.Open();
                OleDbDataAdapter lcoOleDbDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + sheet + "] ", lcoOleDbConnection);
                lcoOleDbDataAdapter.Fill(dsExcel);
                lcoOleDbConnection.Close();
                int flag = 0;
                DataTable dtData = new DataTable();
                if (dsExcel.Tables.Count > 0)
                {
                    dtData = dsExcel.Tables[0];
                    dtExcel = dtData.Clone();
                    for (int numfil = 0; numfil < dtData.Rows.Count; numfil++)
                    {
                        flag = 0;
                        for (int numcol = 0; numcol < dtData.Columns.Count; numcol++)
                        {
                            if (dtData.Rows[numfil][numcol].ToString().Trim() != "")
                            {
                                flag = 1;
                            }
                        }

                        if (flag == 1)
                        {
                            dtExcel.Rows.Add(dtData.Rows[numfil].ItemArray);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                lcoOleDbConnection.Close();
            }
            catch (Exception ex)
            {
                if (lcoOleDbConnection.State == ConnectionState.Open)
                    lcoOleDbConnection.Close();
                throw ex;//UTConstantes.MENSAJE.ERROR_LECTURA);
            }
            return dtExcel;
        }

        public string getFirstSheet(string ExcelFile)
        {
            string sheetName = "";
            OleDbConnection lcoOleDbConnection = null;
            System.Data.DataTable dt = null;
            try
            {
                string connectionString = "";
                if (ExcelFile.Trim().ToUpper().EndsWith("XLS"))
                {
                    connectionString = string.Format(ConfigUtil.readConnectionString("EXCEL_CS"), ExcelFile);
                }
                else
                {
                    connectionString = string.Format(ConfigUtil.readConnectionString("EXCEL_CS_2007"), ExcelFile);
                }
                lcoOleDbConnection = new OleDbConnection(connectionString);
                lcoOleDbConnection.Open();
                dt = lcoOleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                foreach (DataRow row in dt.Rows)
                {
                    sheetName = row["TABLE_NAME"].ToString();
                    break;
                }
                lcoOleDbConnection.Close();
            }
            catch (Exception)
            {
                if (lcoOleDbConnection.State == ConnectionState.Open)
                    lcoOleDbConnection.Close();
            }
            return sheetName;
        }

        public void ExportarExcelWeb(WebControl wc, HttpResponse Response, HttpRequest Request, HttpServerUtility Server)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                Page page = new Page();

                HtmlForm form = new HtmlForm();
                wc.EnableViewState = false;
                page.EnableEventValidation = false;
                page.DesignerInitialize();

                HtmlLink link = new HtmlLink();
                string urlEstilos = this.AbsolutePath(Request, ConfigUtil.readValue("cssExcel"));
                link.Attributes.Add("href", urlEstilos);
                link.Attributes.Add("type", "text/css");
                link.Attributes.Add("rel", "stylesheet");
                page.Controls.Add(link);

                page.Controls.Add(form);

                form.Controls.Add(wc);

                page.RenderControl(htw);
                Response.Clear();
                Response.Buffer = true;
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", "attachment;filename=ArchivoExportarExcel.xls");
                Response.Charset = "UTF-8";
                Response.ContentEncoding = Encoding.Default;

                Response.Write(sb.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected string AbsolutePath(HttpRequest Request, String file)
        {
            String end = (Request.ApplicationPath.EndsWith("/")) ? "" : "/";
            String path = Request.ApplicationPath + end;
            String url = Request.Url.Authority;
            return String.Format("http://{0}{1}{2}", url, path, file);
        }

        #endregion

        #endregion
    }

}
